package com.linzi.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * http请求
 *
 * @author chenmaolin
 * @date: 2022/3/3 15:12
 */
@Slf4j
public class RequestUtils {

    public static JSONArray postList(RestTemplate restTemplate, String url, MultiValueMap<String, Object> map) {
        HttpHeaders headers = new HttpHeaders();
        // 接口参数
        if (map == null) {
            map = new LinkedMultiValueMap<>();
        }
        // 头部类型
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
        try {
            // 发起请求,服务地址，请求参数，返回消息体的数据类型
            ResponseEntity<String> response = restTemplate.postForEntity(url, param, String.class);
            // body
            JSONObject body = JSONObject.parseObject(response.getBody());
            int code = body.getInteger("code");
            if (code == HttpStatus.OK.value()) {
                return body.getJSONArray("result");
            }
        } catch (Exception e) {
            log.error("请求异常>>>>>>>>>>>", e);
        }
        return null;
    }

}
